import React, { useMemo, useState } from 'react';
import { Button, Modal, Input, Form, Select, InputNumber, Radio, Col,message  } from 'antd';
import { connect, history } from 'umi';
import { saveMemberSigned,saveBookingCourse,cancelSign } from '@/pages/reservation/service';
const FormItem = Form.Item;
const { TextArea } = Input;

const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 5,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 18,
        },
        md: {
            span: 18,
        },
    },
};
const submitFormLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 18,
            offset: 5,
        },
    },
};

const MemberCardTypeMap={
    '1':'储值类型',
    '2':'次卡类型',
    '3':'期限类型',
    '4':'器械类型'
}
const ResevationSave = (props) => {
    const { member,membersList, membersCardList, submitting,visible,dispatch,close,classId,onReload } = props
    const [form] = Form.useForm();
    const closeModal = () => {
        form.resetFields();
        dispatch({
            type: 'cubeReservation/reset'
        })
        close && close();
    }
    const options = useMemo(()=>{
        return membersList.map(d => <Option key={d.id}>{d.name}({d.phone})</Option>)
    },[membersList]);
    //会员查询
    const handleSearch = (value) => {
        if (value) {
            let timeout;
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            function fake() {
                dispatch({
                    type: 'cubeReservation/fetchMembersList',
                    payload: {
                        text: value
                    },
                })
            }
            timeout = setTimeout(fake, 500);
        } else {
            dispatch({
                type: 'cubeReservation/common',
                payload: {
                    membersList: []
                },
            });
        }
    }

    //选择会员
    const handleSelect = value => {
        //检索会员基本信息
        let member = membersList.filter((item) => {
            return item.id == value;
        });
        if (!!member && member.length > 0) {
            dispatch({
                type: 'cubeReservation/common',
                payload: {
                    member: member[0]
                },
            });
        } else {
            dispatch({
                type: 'cubeReservation/common',
                payload: {
                    member: null
                },
            });
        }
        dispatch({
            type: 'cubeReservation/getMemberCard',
            payload: {
                memberId: value,
            },
        });
    }
    const hideModal = () => {
        dispatch({
            type: 'cubeReservation/reset'
        })
        close && close();
      };
    //添加预约
    const onFinish = async (values, callback) => {
        const hide = message.loading('正在添加');
        values.classId = classId
        values.memberId = member.id
        try {
            let result = await saveBookingCourse({ ...values });
            hide();
            if (result.code == 0) {
                callback && callback()
                hideModal();
                message.success('添加成功');
                //刷新课程预约人数
                onReload && onReload();
                form.resetFields();
                return true;
            } else {
                message.success(result.message);
                return false;
            }
        } catch (error) {
            hide();
            console.log('error>>>',error)
            message.error('添加失败，请重试！');
            return false;
        }
    }
    const renderCardInfo = (cardInfo) =>{
        let text = `${cardInfo?.cardName}-${MemberCardTypeMap[cardInfo.cardType]}`;
        return text;
    }
    return <Modal
        title="添加预约"
        visible={visible}
        onCancel={closeModal}
        footer={null}
    >
        <Form
            style={{
                marginTop: 8,
            }}
            form={form}
            name="basic"
            onFinish={onFinish}
            initialValues={{
                bookingNum: 1
            }}
        >
            <FormItem
                {...formItemLayout}
                label="会员"
                name="member"
            >
                <Select
                    showSearch
                    placeholder="请输入会员姓名或者手机号码"
                    showArrow={false}
                    filterOption={false}
                    onSearch={handleSearch}
                    onSelect={handleSelect}
                    notFoundContent={null}
                >
                    {options}
                </Select>
            </FormItem>
            {!!member &&
                <>
                    <FormItem
                        {...formItemLayout}
                        label="姓名"
                        name="name"
                    >
                        <span>{member.name}</span>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="性别"
                        name="sex"
                    >
                        <span>{member.sex == '1' ? '男' : member.sex == '2' ? '女' : '未设置'}</span>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="电话"
                        name="phone"
                    >
                        <span>{member.phone}</span>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="预约人数"
                        name="bookingNum"
                    >
                        <InputNumber
                            min={0}
                            style={{ width: '100%' }}
                            formatter={value => `${value}人`}
                            parser={value => value.replace('人', '')}
                        />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="预约会员卡"
                        name="cardId"
                        rules={[
                            {
                                required: true,
                                message: '请选择预约会员卡',
                            },
                        ]}
                    >
                        {
                            membersCardList && membersCardList.length > 0 ?
                                <Radio.Group>
                                    {
                                        membersCardList && membersCardList.map((item, index) => <Col span={24}><Radio value={item.cardId} key={index}>{renderCardInfo(item)}</Radio></Col>)
                                    }
                                </Radio.Group> : "当前没有可用会员卡"
                        }
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="备注"
                        name="zb"
                    >
                        <TextArea rows={4} placeholder="请输入" />
                    </FormItem>
                    <FormItem
                        {...submitFormLayout}
                        style={{
                            marginTop: 32,
                        }}
                    >
                        <Button type="primary" htmlType="submit" loading={submitting}>
                            确认预约
                        </Button>
                    </FormItem>
                </>
            }
        </Form>
    </Modal>
}
export default connect(({ loading, cubeReservation }) => ({
    submitting: loading.effects['cubeReservation/add'],
    membersList: cubeReservation.membersList,
    member: cubeReservation.member,
    membersCardList: cubeReservation.membersCardList,
    classTableInfoList: cubeReservation.classTableInfoList,
    memberBookInfoList: cubeReservation.memberBookInfoList,
    shopList: cubeReservation.shopList,
    coachList: cubeReservation.coachList,
    timeList: cubeReservation.timeList,
}))(ResevationSave);
